package ntu.metaweb.storage;

import java.io.IOException;

import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import ntu.p2p.dht.DHTContentKey;

public class PagesWithTagKey implements DHTContentKey {

	private Id id;
	private String tag;
	
	public static PagesWithTagKey build (InputBuffer buf, Endpoint endpoint)
			throws IOException {
		return new PagesWithTagKey(buf, endpoint);
	}
	
	public PagesWithTagKey(String tag) {
		this.id = rice.pastry.Id.build(("tag_" + tag).getBytes());
		this.tag = tag;
	}
	
	protected PagesWithTagKey(InputBuffer buf, Endpoint endpoint) 
			throws IOException {
		this.id = endpoint.readId(buf, buf.readShort());
		this.tag = buf.readUTF();
	}
	
	@Override
	public Id getId() {
		return id;
	}

	@Override
	public void serialize(OutputBuffer buf) throws IOException {
		buf.writeShort(this.id.getType());
		this.id.serialize(buf);
		buf.writeUTF(tag);
	}
	
	public int hashCode() {
		return id.hashCode() + tag.hashCode();
	}
	
	public boolean equals(Object o) {
		if ((o == null) || !(o instanceof PagesWithTagKey))
			return false;
		PagesWithTagKey key = (PagesWithTagKey) o;
		return this.id.equals(key.id) && this.tag.equals(key.tag);
	}

}
